package com.zhoug.zmui3;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;

import com.zhoug.common3.filters.PhoneFormat;
import com.zhoug.common3.view.edit.ZMUIEditText;

import androidx.annotation.Nullable;

/**
 * 电话号码输入框
 *
 * @Author: zhoug
 * @Date: 2024-07-10
 * @Description:
 */
public class ZMUIPhoneEditText extends ZMUIEditText {
    private boolean isPhone334;//手机号显示成334格式,其他输入不限制 eg:135 2514 3654 格式
    private boolean forcePhone;//强制限制输入为手机号码
    private Phone334TextWatcher mPhone334TextWatcher;

    public ZMUIPhoneEditText(Context context) {
        this(context, null);
    }

    public ZMUIPhoneEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public ZMUIPhoneEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);

    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ZMUIPhoneEditText, defStyleAttr, 0);
        isPhone334 = a.getBoolean(R.styleable.ZMUIPhoneEditText_zmui_isPhone334, false);
        forcePhone = a.getBoolean(R.styleable.ZMUIPhoneEditText_zmui_forcePhone, true);
        a.recycle();
        setPhone334(isPhone334);

    }


    @Nullable
    @Override
    public Editable getText() {
        return super.getText();
    }

    public void setPhone334(boolean isPhone334) {
        this.isPhone334 = isPhone334;
        if (mPhone334TextWatcher != null) {
            removeTextChangedListener(mPhone334TextWatcher);
        }
        if (isPhone334) {
            if (mPhone334TextWatcher == null) {
                mPhone334TextWatcher = new Phone334TextWatcher();
            }
            addTextChangedListener(mPhone334TextWatcher);
        }
    }

    public String getPhoneNumber() {
        if (isPhone334) {
            return PhoneFormat.getPhoneNumber(getText());
        }
        Editable text = getText();
        return text != null ? text.toString().trim() : null;
    }

    private class Phone334TextWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }


        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(isPhone334){
                if(forcePhone){
                    PhoneFormat.onTextChanged344(self(), s);
                }else{
                    PhoneFormat.afterTextChangedIf334(self(), s);
                }
            }
        }
    }

    private ZMUIPhoneEditText self(){
        return this;
    }
}
